<?php
defined ( 'BASEPATH' ) or exit ( 'No direct script access allowed' );
class Department extends CI_Controller {
	public function __construct() {
		parent::__construct ();
		if (! $this->session->userdata ( 'logged_in' )) {
			redirect ( 'index_admin/login' );
			exit ();
		}
	}
	/*
	 * 返回部门管理主页
	 */
	public function index() {
		$this->load->model ( 'department_model' );
		$data ['departments'] = $this->department_model->find_all_departments ();
		$data ['title'] = '部门管理 - 员工管理系统';
		$this->load->view ( 'header', $data );
		$this->load->view ( 'department/index' );
		$this->load->view ( 'footer' );
	}
	/*
	 * 返回添加部门页面
	 */
	public function add() {
		$data ['title'] = '添加部门 - 员工管理系统';
		$this->load->view ( 'header', $data );
		$this->load->view ( 'department/add' );
		$this->load->view ( 'footer' );
	}
	/*
	 * 返回编辑部门页面
	 */
	public function edit() {
		$id = $this->uri->segment(4);
		$this->load->model ( 'department_model' );
		$data ['department'] = $this->department_model->load ( $id );
		$data ['title'] = '编辑部门 - 员工管理系统';
		$this->load->view ( 'header', $data );
		$this->load->view ( 'department/edit' );
		$this->load->view ( 'footer' );
	}
	/*
	 * 保存或者更新部门的信息
	 */
	public function save() {
		$id = $this->input->post('id');
		$department = array (
				'name' => $this->input->post ( 'name' )
		);
		$this->load->model ( 'department_model' );
		if ($id) {
			if($this->department_model->update ( $id, $department )){
				return_json(TRUE,'','修改成功！'); 
			}else{
				return_json(FALSE,'','信息未改动！');
			}
		} else {
			$departmentid=$this->department_model->create ( $department );
			if(!empty($departmentid)){
				return_json(TRUE,'','添加成功！'); 
			}else{
				return_json(FALSE,'','添加失败！');
			}
		}
	}
	/*
	 * 删除部门信息
	 */
	public function delete() {
		$id = $this->input->post('id');
		$this->load->model ( 'staff_model' );
		$staffs = $this->staff_model->find_staffs_by_dep( $id );
		if (! empty ($staffs)) {
			return_json(FALSE,'','该部门下还有员工，不能删除！'); 
		}
		$this->load->model ( 'department_model' );
		if ($this->department_model->delete ( $id )) {
			return_json(TRUE,'','删除成功！'); 
		}else{
			return_json(TRUE,'','删除失败！');
		}
	}
}